package ltd.smallwang;

/**
 * @author smallwang
 * @email justdoalitter@gmail.com
 * @create date 2024-10-07 12:08:27
 * @modify date 2024-10-07 12:08:27
 * @desc [description]
 */
public class Leetcode0138 {
  
  public int canCompleteCircuit(int[] gas, int[] cost) {
    int len = gas.length;
    int[] record = new int[gas.length * 2];
    for (int i = 0; i < len; i++) {
      record[i] = gas[i] - cost[i];
      record[i + len] = gas[i] - cost[i];
    }
    for (int i = 0; i < len;) {
      int total = 0;
      for (int j = 0; j < len; j++) {
        total += record[i + j];
        if (total < 0) {
          i = i + j + 1;
          break;
        }
      }
      if (total >= 0) {
        return i;
      }
    }
    return -1;
  }
}
